package com.example.sqlitelogin;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;

import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.example.sqlitelogin.tools.DataChange;
import com.example.sqlitelogin.tools.HttpGetPost;


public class WeatherActivity extends AppCompatActivity {
    private WebView webView;
    private EditText editText;
    private TextView textView;
    private Button date1, date2, date3;
    private TextView temp, direct1, now_direct, now_power, now_aqi, nowdaylight, nowcity;
    private LinearLayout l1, l2, l3, ml;
    private String name, name2, name3, direct, power, aqi, year, month, day, date22, temperature2, weather2, direct2, date33, temperature3, weather3, direct3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weather);

        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        Intent intent1 = getIntent();
        name = intent1.getStringExtra("city");
        name2 = intent1.getStringExtra("temp");
        name3 = intent1.getStringExtra("daylight");
        direct = intent1.getStringExtra("direct");
        power = intent1.getStringExtra("power");
        aqi = intent1.getStringExtra("aqi");
        year = intent1.getStringExtra("year");
        month = intent1.getStringExtra("month");
        day = intent1.getStringExtra("day");


        date22 = intent1.getStringExtra("date2");
        temperature2 = intent1.getStringExtra("temperature2");
        weather2 = intent1.getStringExtra("weather2");
        direct2 = intent1.getStringExtra("direct2");
        date33 = intent1.getStringExtra("date3");
        temperature3 = intent1.getStringExtra("temperature3");
        weather3 = intent1.getStringExtra("weather3");
        direct3 = intent1.getStringExtra("direct3");


        date1 = findViewById(R.id.date1);
        date2 = findViewById(R.id.date2);
        date3 = findViewById(R.id.date3);
        temp = findViewById(R.id.nowtemp);
        direct1 = findViewById(R.id.direct);
        now_direct = findViewById(R.id.now_direct);
        now_power = findViewById(R.id.now_power);
        now_aqi = findViewById(R.id.now_aqi);
        nowdaylight = findViewById(R.id.nowdaylight);
        nowcity = findViewById(R.id.nowcity);
        ml = findViewById(R.id.ml1);


        temp.setText(name2 + "℃");
        now_direct.setText(direct);
        now_power.setText(power);

        nowdaylight.setText(name3);
        direct1.setText(direct);

        now_aqi.setText(aqi + "%");
        direct1.setVisibility(direct1.INVISIBLE);
        date1.setText(year + "-" + month + "-" + day);

        date2.setText(date22);
        date3.setText(date33);

        if (DataChange.Cty != null) {
            nowcity.setText("当前城市" + DataChange.Cty);
            temp.setText(DataChange.Te + "℃");
            nowdaylight.setText(DataChange.dalt);

            now_direct.setText(DataChange.direct);
            now_power.setText(DataChange.power);
            now_aqi.setText(DataChange.aqi);

            temperature2 = DataChange.te1;
            temperature3 = DataChange.te2;
            weather2 = DataChange.weather11;
            weather3 = DataChange.weather22;
            direct2 = DataChange.direct1;
            direct3 = DataChange.direct2;

        }

        TextView locat;
        locat = findViewById(R.id.locat123);

        // 创建LocationManager对象
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

// 获取最后一次定位信息
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        double latitude=0;
        double longitude=0;
        if (location != null) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            // 在这里处理获取到的经纬度信息
        }
        String loac1 = String.format("%.2f",latitude);
        String loac2 = String.format("%.2f",longitude);
        locat.setText("当前所在经纬度:"+loac1+","+loac2);
        Button button123=findViewById(R.id.search1);
        EditText edit=findViewById(R.id.city_search);

        date1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                date1.setBackground(getResources().getDrawable(R.drawable.shape_bg_blue));
                date1.setTextColor(getResources().getColor(R.color.white));
                date2.setBackground(getResources().getDrawable(R.drawable.shape_bg_white));
                date2.setTextColor(getResources().getColor(R.color.black));
                date3.setBackground(getResources().getDrawable(R.drawable.shape_bg_white));
                date3.setTextColor(getResources().getColor(R.color.black));

                direct1.setVisibility(direct1.INVISIBLE);
                now_direct.setVisibility(now_direct.VISIBLE);
                now_power.setVisibility(now_power.VISIBLE);
                now_aqi.setVisibility(now_aqi.VISIBLE);
                ml.setVisibility(ml.VISIBLE);

                temp.setText(name2+"℃");
                nowdaylight.setText(name3);
                now_direct.setText(direct);
                now_power.setText(power);
                now_aqi.setText(aqi+"%");


            }
        });

        date2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                date1.setBackground(getResources().getDrawable(R.drawable.shape_bg_white));
                date1.setTextColor(getResources().getColor(R.color.black));
                date2.setBackground(getResources().getDrawable(R.drawable.shape_bg_blue));
                date2.setTextColor(getResources().getColor(R.color.white));
                date3.setBackground(getResources().getDrawable(R.drawable.shape_bg_white));
                date3.setTextColor(getResources().getColor(R.color.black));

                direct1.setVisibility(direct1.VISIBLE);
                now_direct.setVisibility(now_direct.INVISIBLE);
                now_power.setVisibility(now_power.INVISIBLE);
                now_aqi.setVisibility(now_aqi.INVISIBLE);
                ml.setVisibility(ml.INVISIBLE);

                direct1.setText(direct2);
                temp.setText(temperature2);
                nowdaylight.setText(weather2);
            }
        });

        date3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                date1.setBackground(getResources().getDrawable(R.drawable.shape_bg_white));
                date1.setTextColor(getResources().getColor(R.color.black));
                date2.setBackground(getResources().getDrawable(R.drawable.shape_bg_white));
                date2.setTextColor(getResources().getColor(R.color.black));
                date3.setBackground(getResources().getDrawable(R.drawable.shape_bg_blue));
                date3.setTextColor(getResources().getColor(R.color.white));

                direct1.setVisibility(direct1.VISIBLE);
                now_direct.setVisibility(now_direct.INVISIBLE);
                now_power.setVisibility(now_power.INVISIBLE);
                now_aqi.setVisibility(now_aqi.INVISIBLE);
                ml.setVisibility(ml.INVISIBLE);

                direct1.setText(direct3);
                temp.setText(temperature3);
                nowdaylight.setText(weather3);

            }
        });

        button123.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String city_name=edit.getText().toString().trim();

                 int nl=city_name.indexOf("市");

                 if (nl==-1){

                     String jsonStr = "";
                     String strUrl = "http://apis.juhe.cn/simpleWeather/query";
                     String srtVlaue = "city=" + city_name + "&key=7745e843fd2ccf00611fccc2a305d205";
                     jsonStr = HttpGetPost.sendGet(strUrl, srtVlaue);
                     Log.e("leo", jsonStr);
                     JSONObject json = JSON.parseObject(jsonStr);


                      name2= (String) json.getJSONObject("result").getJSONObject("realtime").get("temperature");
                      name3 = (String) json.getJSONObject("result").getJSONObject("realtime").get("info");
                     direct = (String) json.getJSONObject("result").getJSONObject("realtime").get("direct");
                     power = (String) json.getJSONObject("result").getJSONObject("realtime").get("power");
                     aqi = (String) json.getJSONObject("result").getJSONObject("realtime").get("aqi");

                     JSONObject js=json.getJSONObject("result");
                     JSONArray gj=js.getJSONArray("future");

                     JSONObject getJsonObj = gj.getJSONObject(1);//获取json数组中的第二项
                      date22=(String) getJsonObj.get("date");
                      temperature2=(String) getJsonObj.get("temperature");
                      weather2=(String) getJsonObj.get("weather");
                      direct2=(String) getJsonObj.get("direct");

                     JSONObject tJsonObj = gj.getJSONObject(1);//获取json数组中的第一项

                      date33=(String) tJsonObj.get("date");
                      temperature3=(String) tJsonObj.get("temperature");
                      weather3=(String) tJsonObj.get("weather");
                      direct3=(String) tJsonObj.get("direct");

                     date1.setBackground(getResources().getDrawable(R.drawable.shape_bg_blue));
                     date1.setTextColor(getResources().getColor(R.color.white));
                     date2.setBackground(getResources().getDrawable(R.drawable.shape_bg_white));
                     date2.setTextColor(getResources().getColor(R.color.black));
                     date3.setBackground(getResources().getDrawable(R.drawable.shape_bg_white));
                     date3.setTextColor(getResources().getColor(R.color.black));

                     direct1.setVisibility(direct1.INVISIBLE);
                     now_direct.setVisibility(now_direct.VISIBLE);
                     now_power.setVisibility(now_power.VISIBLE);
                     now_aqi.setVisibility(now_aqi.VISIBLE);
                     ml.setVisibility(ml.VISIBLE);

                     nowcity.setText("当前城市"+city_name);
                     temp.setText(name2+"℃");
                     nowdaylight.setText(name3);
                     now_direct.setText(direct);
                     now_power.setText(power);
                     now_aqi.setText(aqi+"%");

                     DataChange.Te=name2;
                     DataChange.dalt=name3;
                     DataChange.Cty=city_name;

                     DataChange.aqi=aqi;
                     DataChange.direct=direct;
                     DataChange.power=power;

                     DataChange.te1=temperature2;
                     DataChange.weather11=weather2;
                     DataChange.direct1=direct2;
                     DataChange.te2=temperature3;
                     DataChange.weather22=weather3;
                     DataChange.direct2=direct3;
                 }else {
                     String[] strings=city_name.split("市");
                     String gcity=strings[0].toString();
                     Log.e("leo",gcity);


                     String jsonStr = "";
                     String strUrl = "http://apis.juhe.cn/simpleWeather/query";
                     String srtVlaue = "city=" + gcity + "&key=ab07106ead418d5b395fe9a58e241fbd";
                     jsonStr = HttpGetPost.sendGet(strUrl, srtVlaue);
                     Log.e("leo", jsonStr);
                     JSONObject json = JSON.parseObject(jsonStr);

                     name2= (String) json.getJSONObject("result").getJSONObject("realtime").get("temperature");
                     name3 = (String) json.getJSONObject("result").getJSONObject("realtime").get("info");
                     direct = (String) json.getJSONObject("result").getJSONObject("realtime").get("direct");
                     power = (String) json.getJSONObject("result").getJSONObject("realtime").get("power");
                     aqi = (String) json.getJSONObject("result").getJSONObject("realtime").get("aqi");

                     JSONObject js=json.getJSONObject("result");
                     JSONArray gj=js.getJSONArray("future");


                     JSONObject getJsonObj = gj.getJSONObject(1);//获取json数组中的第二项
                     date22=(String) getJsonObj.get("date");
                     temperature2=(String) getJsonObj.get("temperature");
                     weather2=(String) getJsonObj.get("weather");
                     direct2=(String) getJsonObj.get("direct");

                     JSONObject tJsonObj = gj.getJSONObject(2);//获取json数组中的第三项

                     date33=(String) tJsonObj.get("date");
                     temperature3=(String) tJsonObj.get("temperature");
                     weather3=(String) tJsonObj.get("weather");
                     direct3=(String) tJsonObj.get("direct");

                     date1.setBackground(getResources().getDrawable(R.drawable.shape_bg_blue));
                     date1.setTextColor(getResources().getColor(R.color.white));
                     date2.setBackground(getResources().getDrawable(R.drawable.shape_bg_white));
                     date2.setTextColor(getResources().getColor(R.color.black));
                     date3.setBackground(getResources().getDrawable(R.drawable.shape_bg_white));
                     date3.setTextColor(getResources().getColor(R.color.black));

                     direct1.setVisibility(direct1.INVISIBLE);
                     now_direct.setVisibility(now_direct.VISIBLE);
                     now_power.setVisibility(now_power.VISIBLE);
                     now_aqi.setVisibility(now_aqi.VISIBLE);
                     ml.setVisibility(ml.VISIBLE);

                     nowcity.setText("当前城市"+gcity);
                     temp.setText(name2+"℃");
                     nowdaylight.setText(name3);
                     now_direct.setText(direct);
                     now_power.setText(power);
                     now_aqi.setText(aqi+"%");


                     DataChange.Te=name2;
                     DataChange.dalt=name3;
                     DataChange.Cty=gcity;

                     DataChange.aqi=aqi;
                     DataChange.direct=direct;
                     DataChange.power=power;

                     DataChange.te1=temperature2;
                     DataChange.weather11=weather2;
                     DataChange.direct1=direct2;
                     DataChange.te2=temperature3;
                     DataChange.weather22=weather3;
                     DataChange.direct2=direct3;
                 }

            }
        });

    }
    //url抓取数据（参数URL：就是你要抓数据的地址。如：http://www.cnev.cn/）
    public static String urlClimb(String url) throws Exception{
        URL getUrl =new URL(url); //创建URl连接
        HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection(); //建立连接
        connection.connect(); //打开连接
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8")); //创建输入流并设置编码
        StringBuffer sb = new StringBuffer();
        String lines = null;
        while ((lines = reader.readLine()) != null) {
            lines = new String(lines.getBytes(), "utf-8"); //读取流的一行,设置编码
            sb = sb.append(lines + "\n");
        }
        reader.close(); //关闭流
        connection.disconnect(); //销毁连接

        return sb.toString(); //返回抓取的数据(注意,这里是抓取了访问的网站的全部数据)
    }

    //正则筛选(抓取了访问的网站的全部数据的字符串,就是上面那两个方法其中一个返回的result)
    public static String choosePattern(String result){
        String regex = "<span class=\".*\">.*</span>"; //这个正则表达式是取所有span标签
        StringBuffer sb = new StringBuffer();
        //Pattern类编译正则表达式(后面的Pattern静态属性是忽略大小写)
        Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(result); //Matcher类是搜索匹配内容(下面也简单写上Matcher类的解释)
        while (matcher.find()) {
            sb.append(matcher.group(0)+"\n"); //匹配整个正则表达式,并返回该行字符串
        }
        return sb.toString(); //把匹配的内容返回
    }

    //启用不区分大小写的匹配
    public static final int CASE_INSENSITIVE = 0x02;
    //模式中允许空白和注释。
    public static final int COMMENTS = 0x04;
    //启用多行模式。
    public static final int MULTILINE = 0x08;
    //启用模式的字面值解析。
    public static final int LITERAL = 0x10;
    //启用 dotall 模式。
    public static final int DOTALL = 0x20;
    //启用 Unicode 感知的大小写折叠。
    public static final int UNICODE_CASE = 0x40;
    //启用规范等价
    public static final int CANON_EQ = 0x80;
    private static final long serialVersionUID = 5073258162644648461L;
    // 获得屏幕的宽度
//    public static int getScreenWidth(Context ctx) {
//        // 从系统服务中获取窗口管理器
//        WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);
//        DisplayMetrics dm = new DisplayMetrics();
//        // 从默认显示器中获取显示参数保存到dm对象中
//        wm.getDefaultDisplay().getMetrics(dm);
//        return dm.widthPixels; // 返回屏幕的宽度数值
//    }
//
//    // 获得屏幕的高度
//    public static int getScreenHeight(Context ctx) {
//        // 从系统服务中获取窗口管理器
//        WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);
//        DisplayMetrics dm = new DisplayMetrics();
//        // 从默认显示器中获取显示参数保存到dm对象中
//        wm.getDefaultDisplay().getMetrics(dm);
//        return dm.heightPixels; // 返回屏幕的高度数值
//    }



}
